package com.fhnew.app.ui.activity.main.option;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.GridLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.fhnew.app.R;
import com.fhnew.app.global.Constants;
import com.fhnew.app.model.internet.HttpAPI;
import com.fhnew.app.model.internet.HttpRequest;
import com.fhnew.app.model.internet.been.B_CommonGames;
import com.fhnew.app.model.internet.been.B_GameWebUrl;
import com.fhnew.app.model.internet.been.B_HotList;
import com.fhnew.app.model.internet.been.B_SLGames;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.model.network.entity.req.GameData;
import com.fhnew.app.ui.activity.X5WebActivity;
import com.fhnew.app.widget.LoadingDialog;
import com.fhnew.app.ui.dialogactivity.LoginDiolog;
import com.fhnew.app.util.HLog;
import com.fhnew.app.widget.GameItemView;
import com.fhnew.app.widget.GameListView;

import java.util.ArrayList;
import java.util.List;


/**
 * 控制游戏列表的显示
 * 1、构造函数 {@link GameListOption#GameListOption}
 * <p>
 * 2、显示不同游戏列表的函数
 * 一级：{@link GameListOption#showGameList}
 * 二级：
 * 显示棋牌 {@link GameListOption#showSecodLevel02}
 * 显示网络中获取的列表 {@link GameListOption#showSecodLevelInternet}
 * <p>
 * 3、创建ItemView控件   {@link GameListOption#createGameItem}
 * <p>
 * 4、点击事件处理函数  {@link GameListOption#onClickListener}
 * <p>
 * 5、网络请求
 * 获取热门游戏列表：{@link GameListOption#getHotList}
 * 获取游戏列表：{@link GameListOption#getCommonGames}
 * 获取游戏二级列表： {@link GameListOption#getGameSecondLeveList}
 * 获取游戏url：  {@link GameListOption#getGameUrl}
 * <p>
 * 6、点击事件解析函数
 * 创建事件值 {@link GameListOption#makeIndex}
 * 解析事件值 {@link GameListOption#getIndex}
 */
public class GameListOption {

    private GameListView gameListView;
    private HorizontalScrollView gameListScrollView;
    private Context context;
    private CommendGameChangedListener commendGameChangedListener;

    private B_HotList b_hotList;
    private B_CommonGames b_commonGames;

    private int firstLevelIndex = -1;

    private GameData gameData;

    private UserModel userModel;

    private LoadingDialog loadingDialog;


    public GameListOption(HorizontalScrollView gameListScrollView, GameListView gameListView, LoadingDialog loadingDialog, CommendGameChangedListener commendGameChangedListener) {

        context = gameListScrollView.getContext();
        userModel = UserModel.getInstance(context);

        this.gameListView = gameListView;
        this.gameListScrollView = gameListScrollView;
        this.commendGameChangedListener = commendGameChangedListener;

        gameData = new GameData();

        getHotList.startRequest();
        getCommonGames.startRequest();

        this.loadingDialog = loadingDialog;
        loadingDialog.setDialogCancelable(false);
        loadingDialog.setShowTips(true);
        loadingDialog.setLodingDialogListener(lodingDialogListener);
        loadingDialog.showLoading();

    }


    public void showGameList(int index) {

        if (index == 1 && b_hotList == null) {
            return;
        } else if (index != 1 && b_commonGames == null) {
            return;
        }

        if (firstLevelIndex == index) {
            gameListScrollView.scrollTo(0, 0);
            gameListScrollView.smoothScrollTo(0, 0);
            gameListView.startAnimator();
            return;
        }

        firstLevelIndex = index;
        gameListView.removeAllViews();
        if (usedView == null)
            usedView = new ArrayList<>();
        usedView.clear();


        switch (index) {
            case 1://热门游戏
                gameListView.setRowCount(2);

                List<B_HotList.DataBean.AHotBean> thirdBeans = b_hotList.getData().getAHot();
                for (int i = 0; i < thirdBeans.size(); i++) {
                    GameItemView gameItemView = createGameItem(index, (i + 1), (0));
                    B_HotList.DataBean.AHotBean thirdBean = thirdBeans.get(i);
                    gameItemView.setGameId(thirdBean.getGame_id());
                    gameItemView.setGameTag(thirdBean.getTag());
                    gameItemView.setOpen_directly(1);
                    Glide.with(context).load(Constants.adress + thirdBeans.get(i).getImg()).placeholder(R.mipmap.nodataimg).into(gameItemView);
                    usedView.add(gameItemView);
                }
                break;
            case 2://棋牌游戏
                gameListView.setRowCount(1);
                List<B_CommonGames.DataBean.PVPBean> PVP = b_commonGames.getData().getPVP();
                for (int i = 0; i < PVP.size(); i++) {
                    if (PVP.get(i).getStatus() == 1) {
                        GameItemView gameItemView = createGameItem(index, (i + 1), (0));
                        gameItemView.setGameId(PVP.get(i).getGame_id());
                        gameItemView.setOpen_directly(0);
                        Glide.with(context).load(gameData.allgameimg[PVP.get(i).getGame_id()]).placeholder(R.mipmap.nodataimg).into(gameItemView);
                        usedView.add(gameItemView);
                    }
                }
                break;
            case 3://捕鱼游戏
                gameListView.setRowCount(1);
                List<B_CommonGames.DataBean.FISHBean> fishBeans = b_commonGames.getData().getFISH();
                for (int i = 0; i < fishBeans.size(); i++) {
                    if (fishBeans.get(i).getStatus() == 1) {
                        GameItemView gameItemView = createGameItem(index, (i + 1), (0));
                        gameItemView.setGameId(fishBeans.get(i).getGame_id());
                        gameItemView.setOpen_directly(fishBeans.get(i).getOpen_directly());
                        gameItemView.setGameTag("5");
                        Glide.with(context).load(gameData.allgameimg[fishBeans.get(i).getGame_id()]).placeholder(R.mipmap.nodataimg).into(gameItemView);
                        usedView.add(gameItemView);
                    }
                }
                break;
            case 4://电竞游戏
                gameListView.setRowCount(1);
                List<B_CommonGames.DataBean.YOPLAYBean> yoplayBeans = b_commonGames.getData().getYOPLAY();
                for (int i = 0; i < yoplayBeans.size(); i++) {
                    if (yoplayBeans.get(i).getStatus() == 1) {
                        GameItemView gameItemView = createGameItem(index, (i + 1), (0));
                        gameItemView.setGameId(yoplayBeans.get(i).getGame_id());
                        gameItemView.setOpen_directly(yoplayBeans.get(i).getOpen_directly());
                        Glide.with(context).load(gameData.allgameimg[yoplayBeans.get(i).getGame_id()]).placeholder(R.mipmap.nodataimg).into(gameItemView);
                        usedView.add(gameItemView);
                    }
                }
                break;
            case 5://电子游戏
                gameListView.setRowCount(2);
                List<B_CommonGames.DataBean.RNGBean> rngBeans = b_commonGames.getData().getRNG();
                for (int i = 0; i < rngBeans.size(); i++) {
                    if (rngBeans.get(i).getStatus() == 1) {
                        GameItemView gameItemView = createGameItem(index, (i + 1), (0), 120, GridLayout.LayoutParams.MATCH_PARENT, MARGIN);
                        gameItemView.setGameId(rngBeans.get(i).getGame_id());
                        gameItemView.setOpen_directly(rngBeans.get(i).getOpen_directly());
                        Glide.with(context).load(gameData.allgameimg[rngBeans.get(i).getGame_id()]).placeholder(R.mipmap.nodataimg).into(gameItemView);
                        usedView.add(gameItemView);
                    }
                }
                break;
            case 6://真人游戏
                gameListView.setRowCount(2);
                List<B_CommonGames.DataBean.LIVEBean> liveBeans = b_commonGames.getData().getLIVE();
                for (int i = 0; i < liveBeans.size(); i++) {
                    if (liveBeans.get(i).getStatus() == 1) {
                        GameItemView gameItemView = createGameItem(index, (i + 1), (0), 120, GridLayout.LayoutParams.MATCH_PARENT, MARGIN);
                        gameItemView.setGameId(liveBeans.get(i).getGame_id());
                        gameItemView.setOpen_directly(liveBeans.get(i).getOpen_directly());
                        Glide.with(context).load(gameData.allgameimg[liveBeans.get(i).getGame_id()]).placeholder(R.mipmap.nodataimg).into(gameItemView);
                        usedView.add(gameItemView);
                    }
                }
                break;
            case 7://体育游戏
                gameListView.setRowCount(1);
                List<B_CommonGames.DataBean.SPORTSBean> sportsBeans = b_commonGames.getData().getSPORTS();
                for (int i = 0; i < sportsBeans.size(); i++) {
                    if (sportsBeans.get(i).getStatus() == 1) {
                        GameItemView gameItemView = createGameItem(index, (i + 1), (0));
                        gameItemView.setGameId(sportsBeans.get(i).getGame_id());
                        gameItemView.setOpen_directly(sportsBeans.get(i).getOpen_directly());
                        Glide.with(context).load(gameData.allgameimg[sportsBeans.get(i).getGame_id()]).placeholder(R.mipmap.nodataimg).into(gameItemView);
                        usedView.add(gameItemView);
                    }
                }
                break;
            case 8://彩票游戏
                gameListView.setRowCount(2);
                List<B_CommonGames.DataBean.LotteryBean> lotteryBeans = b_commonGames.getData().getLottery();
                for (int i = 0; i < lotteryBeans.size(); i++) {
                    if (lotteryBeans.get(i).getRules_status() == 1) {
                        GameItemView gameItemView = createGameItem(index, (i + 1), (0));
                        int gameId = lotteryBeans.get(i).getGame_id();
                        gameItemView.setGameId(gameId);
                        Glide.with(context).load(gameData.lottry(gameId)).placeholder(R.mipmap.nodataimg).into(gameItemView);
                        usedView.add(gameItemView);
                    }
                }
                break;
        }
        gameListView.setGamesView(usedView);
        gameListView.startAnimator();
    }


    private void showSecodLevel02(int gameId) {

        firstLevelIndex = -1;

        gameListScrollView.scrollTo(0, 0);
        gameListScrollView.smoothScrollTo(0, 0);

        gameListView.removeAllViews();
        usedView.clear();

        gameListView.setRowCount(2);

        String[] sTemp = null;
        int[] iTemp = null;

        switch (gameId) {
            case 30://开心棋牌
                sTemp = gameData.kaixinid;
                iTemp = gameData.kaixinpic;
                break;
            case 15://开元棋牌
                sTemp = gameData.kaiyuantag;
                iTemp = gameData.kaiyuanimg;
                break;
            case 16://龙城棋牌
                sTemp = gameData.longchengurl;
                iTemp = gameData.longchengimg;
                break;
            case 31://乐游棋牌
                sTemp = gameData.leyouid;
                iTemp = gameData.leyoupic;
                break;
            case 18://VG棋牌
                sTemp = gameData.vgtag;
                iTemp = gameData.vgiv;

                break;
            case 17://无双棋牌
                sTemp = gameData.wushuangtag;
                iTemp = gameData.wushuangimg;
                break;
            case 10://NN棋牌
                sTemp = gameData.nntag;
                iTemp = gameData.nnimg;
                break;
            case 41://龙游棋牌
                sTemp = gameData.longyoutag;
                iTemp = gameData.longyouimg;
                break;
            default:
                break;
        }
        int secondIndex = gameId;
        if (sTemp != null && iTemp != null) {
            for (int i = 0; i < sTemp.length; i++) {
                GameItemView gameItemView = createGameItem((2), secondIndex, (i + 1));
                gameItemView.setGameTag(sTemp[i]);
                gameItemView.setOpen_directly(1);
                gameItemView.setGameId(gameId);
                Glide.with(context).load(iTemp[i]).placeholder(R.mipmap.nodataimg).into(gameItemView);
                usedView.add(gameItemView);
            }
        }

        gameListView.setGamesView(usedView);
        gameListView.startAnimator();
    }


    private void showSecodLevelInternet(B_SLGames b_slGames) {
        firstLevelIndex = -1;

        gameListScrollView.scrollTo(0, 0);
        gameListScrollView.smoothScrollTo(0, 0);

        gameListView.removeAllViews();
        usedView.clear();

        gameListView.setRowCount(2);

        int index = b_slGames.getIndex();
        int firstIndex = getIndex(index, COVER01);
        int secondIndex = getIndex(index, COVER02);

        for (int i = 0; i < b_slGames.getData().size(); i++) {
            B_SLGames.DataBean dataBean = b_slGames.getData().get(i);
            GameItemView gameItemView = createGameItem(firstIndex, secondIndex, (i + 1));
            gameItemView.setGameTag(dataBean.getTag());
            gameItemView.setGameId(b_slGames.getGameId());
            Glide.with(context).load(dataBean.getUrl()).placeholder(R.mipmap.nodataimg).into(gameItemView);
            usedView.add(gameItemView);
        }
        gameListView.setGamesView(usedView);
        gameListView.startAnimator();
    }


    //===================================================================
    // 点击事件
    //===================================================================

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            GameItemView itemView = (GameItemView) v;

            int index = itemView.getIndex();
            int firstIndex = getIndex(index, COVER01);
            int secodIndex = getIndex(index, COVER02);
            int thirdIndex = getIndex(index, COVER03);

            int gameId = itemView.getGameId();

            HLog.I(HLog.stackTrace() + "点击位置" + firstIndex + "  " + secodIndex + "  " + thirdIndex + "   --" + itemView.getOpen_directly());

            //点击棋牌的一级列表
            if (firstIndex == 2 && thirdIndex == 0) {
                showSecodLevel02(gameId);
                return;
            }

            if (firstIndex == 8) {//彩票暂时不做操作
                return;
            }

            if (!userModel.isLogin()) {
                HLog.I(HLog.stackTrace() + "点击GameItem用户未登录");
                context.startActivity(new Intent(context, LoginDiolog.class));
                return;
            }

            if (itemView.getOpen_directly() == 1) {
                getGameUrl.startRequest(itemView.getGameId(), itemView.getGameTag(), userModel.getToken(), "0");
            } else {
                getGameSecondLeveList.startRequest(gameId, UserModel.Token, index, "2");
            }

        }
    };

    //=====================================================================
    // 网络请求部分
    //=====================================================================
    private HttpRequest httpRequest;

    private HttpAPI.GetHotList getHotList = new HttpAPI.GetHotList() {

        @Override
        public void onStartedRequest(HttpRequest httpRequest) {
            GameListOption.this.httpRequest = httpRequest;
        }

        @Override
        public void result(B_HotList result) {

            HLog.I("热门游戏解析成功"+result.getCode());

            b_hotList = result;
            if (firstLevelIndex < 0)
                showGameList(1);

            loadingDialog.dismiss();
        }

        @Override
        public void error(String msg) {
            Toast.makeText(context, "热门游戏获取失败", Toast.LENGTH_SHORT).show();
            loadingDialog.dismiss();
        }
    };

    private HttpAPI.GetCommonGames getCommonGames = new HttpAPI.GetCommonGames() {
        @Override
        public void result(B_CommonGames result) {
            b_commonGames = result;
            commendGameChangedListener.changed(result);
        }

        @Override
        public void error(String msg) {
            HLog.I("一般游戏列表获取失败" + msg);
        }
    };


    private HttpAPI.GetGameSecondLeveList getGameSecondLeveList = new HttpAPI.GetGameSecondLeveList() {

        public void onStartedRequest(HttpRequest httpRequest) {
            GameListOption.this.httpRequest = httpRequest;
            loadingDialog.showLoading();
        }

        @Override
        public void result(B_SLGames result) {
            loadingDialog.dismiss();
            if (result.getCode() == 600) {
                userModel.loginOut();
                Toast.makeText(context, "登录失效", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(context, LoginDiolog.class);
                context.startActivity(intent);
                return;
            }
            showSecodLevelInternet(result);
        }

        @Override
        public void error(String msg) {
            Toast.makeText(context, "获取游戏列表失败", Toast.LENGTH_SHORT).show();
            loadingDialog.dismiss();
        }
    };

    private HttpAPI.GetGameUrl getGameUrl = new HttpAPI.GetGameUrl() {

        public void onStartedRequest(HttpRequest httpRequest) {
            GameListOption.this.httpRequest = httpRequest;
            loadingDialog.showLoading();
        }

        @Override
        public void result(B_GameWebUrl result) {
            loadingDialog.dismiss();
            if (result.getCode() == 600) {
                userModel.loginOut();
                Toast.makeText(context, "登录失效", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(context, LoginDiolog.class);
                context.startActivity(intent);
                return;
            }
            if (1 == result.getData().oHtml) {
                Uri uri = Uri.parse(result.getData().getUrl() + "");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
            } else {
                HLog.I(HLog.stackTrace() + "加载游戏界面" + result.getData().getGame_id());

//                if (result.getData().getPortrait() == 1) {
////竖屏
//                    WebActivityPortraitGame.startActivity(context, result.getData().getUrl()
//                            , result.getData().getGame_id());
//                } else {
                    X5WebActivity.startActivity(context, result.getData().getUrl()
                            , result.getData().getGame_id(),result.getData().getPortrait());
//                }

            }
//            Uri uri = Uri.parse(result.getData().getUrl() + "");
        }


        @Override
        public void error(String msg) {
            Toast.makeText(context, "获取游戏地址失败", Toast.LENGTH_SHORT).show();
            loadingDialog.dismiss();
        }
    };

    private LoadingDialog.LodingDialogListener lodingDialogListener = new LoadingDialog.LodingDialogListener() {
        @Override
        public void cancelAction() {
            if (GameListOption.this.httpRequest != null)
                GameListOption.this.httpRequest.stopRequest();
        }
    };

    //=====================================================================
    // Item视图创建
    //=====================================================================

    private List<View> usedView;

    private static final int MARGIN = 10;

    private GameItemView createGameItem(int firstIndex, int secodIndex, int thirdIndex) {
        return createGameItem(firstIndex, secodIndex, thirdIndex, GridLayout.LayoutParams.MATCH_PARENT, GridLayout.LayoutParams.MATCH_PARENT, MARGIN);
    }

    private GameItemView createGameItem(int firstIndex, int secodIndex, int thirdIndex, int width, int height, int margin) {

        float density = context.getResources().getDisplayMetrics().density;
        GameItemView imageView = new GameItemView(context);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);

//      imageView.setBackground(context.getDrawable(R.mipmap.kaxin1));

        GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
        layoutParams.bottomMargin = (int) (margin * density);
        layoutParams.topMargin = (int) (margin * density);
        layoutParams.leftMargin = (int) (margin * density);
        layoutParams.rightMargin = (int) (margin * density);

        layoutParams.width = (int) (width * density);
        layoutParams.height = (int) (height * density);

        imageView.setLayoutParams(layoutParams);

        imageView.setIndex(makeIndex(firstIndex, secodIndex, thirdIndex));
        imageView.setOnClickListener(onClickListener);

        return imageView;
    }


    //=====================================================================
    //点击位置的工具函数
    //=====================================================================
    private static final int COVER01 = 0xff000000;
    private static final int COVER02 = 0x00fff000;
    private static final int COVER03 = 0x00000fff;


    /**
     * int4 个字节
     * 0000 0000    |    0000 0000  0000   |   0000  0000 0000
     * 一级游戏列表        二级游戏列表           三级游戏列表
     *
     * @param firstIndex
     * @param secondIndex
     * @param thirdIndex
     * @return
     */
    private int makeIndex(int firstIndex, int secondIndex, int thirdIndex) {
        return firstIndex << 24 | secondIndex << 12 | thirdIndex;
    }

    /**
     * 根据不同掩码获取
     *
     * @param index
     * @param cover
     * @return
     */
    private int getIndex(int index, int cover) {
        if (cover == 0xff000000) {
            return (index & 0xff000000) >> 24;
        } else if (cover == 0x00fff000) {
            return (index & 0x00fff000) >> 12;
        } else if (cover == 0x00000fff) {
            return index & 0x00000fff;
        }
        return 0;
    }


    //========================================================================
    public interface CommendGameChangedListener {

        public void changed(B_CommonGames commonGames);

    }


}
